<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { UserControllerService, FileControllerService } from "../../../generated";
import { Modal, Message } from '@arco-design/web-vue';
import message from "@arco-design/web-vue/es/message";
import {useRouter} from "vue-router";
const router = useRouter();
// 用户数据
const userData = ref({
  id: 0,
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: '',
  createTime: '',
  updateTime: ''
});

// 编辑表单数据
const editForm = ref({
  userName: '',
  userProfile: ''
});

// 加载状态
const loading = ref(true);
// 头像上传状态
const uploading = ref(false);
// 文件输入引用
const fileInput = ref<HTMLInputElement | null>(null);
// 编辑弹窗可见性
const editModalVisible = ref(false);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true;
    const res = await UserControllerService.getLoginUserUsingGet();
    if (res.data) {
      userData.value = {
        ...res.data,
        createTime: formatDate(res.data.createTime),
        updateTime: formatDate(res.data.updateTime)
      };
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    Message.error('获取用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 打开编辑弹窗
const openEditModal = () => {
  editForm.value = {
    userName: userData.value.userName,
    userProfile: userData.value.userProfile
  };
  editModalVisible.value = true;
};

// 提交编辑表单
const submitEditForm = async () => {
  try {
    const res = await UserControllerService.updateMyUserUsingPost({
      userName: editForm.value.userName,
      userProfile: editForm.value.userProfile
    });

    if (res.data) {
      Message.success('资料更新成功');
      await fetchUserInfo();
      editModalVisible.value = false;
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    Message.error('更新用户信息失败');
  }
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click();
};
const handleLogout = async () => {
  const success=await UserControllerService.userLogoutUsingPost();
  if (success) {
    message.success("退出登录成功");
    router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    message.error("退出登录失败");
  }
};

// 上传头像
const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) return;

  try {
    uploading.value = true;
    const res = await FileControllerService.uploadFileUsingPost(
        'user_avatar', // biz参数，表示业务类型为用户头像
        file
    );

    if (res.data) {
      // 假设返回的是完整的URL
      userData.value.userAvatar = res.data;
      // 更新用户头像
      await UserControllerService.updateMyUserUsingPost({
        userAvatar: res.data
      });
      Message.success('头像更新成功');
    }
  } catch (error) {
    console.error('上传头像失败:', error);
    Message.error('上传头像失败');
  } finally {
    uploading.value = false;
    // 清空文件输入，允许重复选择同一文件
    if (target) target.value = '';
  }
};

// 格式化日期为YYYY-MM-DD
const formatDate = (dateString: string | Date) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 角色映射
const roleMap: Record<string, string> = {
  user: '普通用户',
  admin: '管理员',
  ban: '封禁用户'
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<template>
  <div class="user-profile">
    <div class="profile-container">
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
      </div>

      <div class="profile-header">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <div class="avatar-container">
              <img
                  v-if="userData.userAvatar"
                  :src="userData.userAvatar"
                  alt="用户头像"
                  class="user-avatar"
              >
              <div v-else class="avatar-placeholder">
                {{ userData.userName ? userData.userName.charAt(0).toUpperCase() : '' }}
              </div>
              <div v-if="uploading" class="avatar-upload-overlay">
                <div class="upload-spinner"></div>
              </div>
            </div>
            <button
                class="avatar-edit-btn"
                @click="triggerFileInput"
                :disabled="uploading"
            >
              <span class="edit-icon">✏️</span>
              {{ uploading ? '上传中...' : '更换头像' }}
            </button>
            <input
                type="file"
                ref="fileInput"
                accept="image/*"
                @change="handleFileUpload"
                style="display: none;"
            >
          </div>
        </div>

        <div class="user-info-section">
          <h1 class="username">{{ userData.userName }}</h1>
          <div class="user-role" :class="userData.userRole">
            {{ roleMap[userData.userRole] || userData.userRole }}
          </div>
          <p class="user-bio">{{ userData.userProfile || '这个人很懒，还没有写简介~' }}</p>
        </div>
      </div>

      <div class="profile-divider"></div>

      <div class="profile-details">
        <h2 class="section-title">账户信息</h2>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">用户ID</span>
            <span class="info-value">{{ userData.id }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">注册时间</span>
            <span class="info-value">{{ userData.createTime }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">最后更新</span>
            <span class="info-value">{{ userData.updateTime }}</span>
          </div>
        </div>
      </div>

      <div class="profile-actions">
        <button class="action-btn primary" @click="openEditModal">编辑资料</button>
        <button class="action-btn danger" @click="handleLogout">退出登录</button>
      </div>
    </div>

    <!-- 编辑资料弹窗 -->
    <Modal
        v-model:visible="editModalVisible"
        title="编辑资料"
        :mask-closable="false"
        :esc-to-close="false"
        width="500px"
        @ok="submitEditForm"
        @cancel="editModalVisible = false"
    >
      <div class="edit-form">
        <div class="form-item">
          <label class="form-label">用户名</label>
          <a-input
              v-model="editForm.userName"
              placeholder="请输入用户名"
              :max-length="20"
          />
        </div>
        <div class="form-item">
          <label class="form-label">个人简介</label>
          <a-textarea
              v-model="editForm.userProfile"
              placeholder="介绍一下你自己吧~"
              :max-length="200"
              :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </div>
      </div>
    </Modal>
  </div>
</template>

<style scoped>
.user-profile {
  max-width: 900px;
  margin: 40px auto;
  padding: 0 20px;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
}

.profile-container {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.profile-container:hover {
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.15);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(52, 152, 219, 0.2);
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.avatar-container {
  position: relative;
  width: 120px;
  height: 120px;
}

.avatar-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(74, 107, 223, 0.2);
  border-top: 3px solid #4a6bdf;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.profile-header {
  display: flex;
  align-items: flex-start;
  gap: 40px;
  margin-bottom: 30px;
}

.avatar-section {
  flex-shrink: 0;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f2f5;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.03);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.avatar-placeholder {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  font-weight: bold;
  border: 3px solid #f0f2f5;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.avatar-edit-btn {
  background: none;
  border: none;
  color: #4a6bdf;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
  padding: 8px 15px;
  border-radius: 20px;
  background-color: rgba(74, 107, 223, 0.1);
}

.avatar-edit-btn:hover:not(:disabled) {
  background-color: rgba(74, 107, 223, 0.2);
  color: #3a56c0;
}

.avatar-edit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.edit-icon {
  font-size: 12px;
}

.user-info-section {
  flex-grow: 1;
}

.username {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 10px 0;
  color: #1a1a1a;
  letter-spacing: 0.5px;
}

.user-role {
  display: inline-block;
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 15px;
  letter-spacing: 0.5px;
}

.user-role.user {
  background: #e6f7ff;
  color: #1890ff;
}

.user-role.admin {
  background: #fff1f0;
  color: #f5222d;
}

.user-role.ban {
  background: #f5f5f5;
  color: #8c8c8c;
}

.user-bio {
  font-size: 16px;
  line-height: 1.7;
  color: #555;
  margin: 0;
  max-width: 600px;
}

.profile-divider {
  height: 1px;
  background: linear-gradient(to right, transparent, #f0f0f0, transparent);
  margin: 30px 0;
}

.section-title {
  font-size: 22px;
  font-weight: 700;
  margin: 0 0 25px 0;
  color: #1a1a1a;
  position: relative;
  display: inline-block;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(to right, #4a6bdf, #2575fc);
  border-radius: 3px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 14px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-label {
  font-weight: 600;
  color: #666;
  width: 100px;
  flex-shrink: 0;
  font-size: 15px;
}

.info-value {
  color: #1a1a1a;
  font-size: 15px;
  font-weight: 500;
}

.profile-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 40px;
}

.action-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  letter-spacing: 0.5px;
}

.action-btn.primary {
  background: linear-gradient(to right, #4a6bdf, #2575fc);
  color: white;
}

.action-btn.danger {
  background: #fff1f0;
  color: #f5222d;
}

.action-btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
}

/* 编辑表单样式 */
.edit-form {
  padding: 10px 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1a1a1a;
}
</style>
